<template>
  <div class="learning-progress">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="学员姓名">
        <el-input v-model="searchForm.studentName" placeholder="请输入学员姓名" clearable />
      </el-form-item>
      <el-form-item label="教练姓名">
        <el-input v-model="searchForm.coachName" placeholder="请输入教练姓名" clearable />
      </el-form-item>
      <el-form-item label="培训阶段">
        <el-select v-model="searchForm.stage" placeholder="请选择培训阶段" clearable>
          <el-option label="科目一" value="subject1" />
          <el-option label="科目二" value="subject2" />
          <el-option label="科目三" value="subject3" />
          <el-option label="科目四" value="subject4" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 进度表格 -->
    <el-table :data="progressList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="学员编号" width="100" />
        <el-table-column prop="studentName" label="学员姓名" width="120" />
        <el-table-column prop="coachName" label="教练姓名" width="120" />
        <el-table-column prop="registrationDate" label="报名日期" width="140" />
        <el-table-column label="当前科目" width="120">
          <template #default="{ row }">
            {{ getCurrentSubject(row.stages) }}
          </template>
        </el-table-column>
        <el-table-column label="总学时" width="100">
          <template #default="{ row }">
            {{ calculateTotalHours(row.stages) }}课时
          </template>
        </el-table-column>
        <el-table-column label="当前状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="考试状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getExamStatusTagType(row.examStatus)">{{ row.examStatus || '未安排' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="总进度" width="120">
          <template #default="{ row }">
            <el-progress 
              :percentage="calculateTotalProgress(row)" 
              :status="getProgressStatus(row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleViewDetails(row)">查看详情</el-button>
          <el-button link type="success" @click="handleUpdateProgress(row)">更新进度</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 学习进度详情抽屉 -->
    <el-drawer
      v-model="detailDrawerVisible"
      title="学习进度详情"
      size="500px"
      direction="rtl"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学员姓名">{{ currentStudent.studentName }}</el-descriptions-item>
        <el-descriptions-item label="教练姓名">{{ currentStudent.coachName }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="getStatusTagType(currentStudent.status)">{{ currentStudent.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="总进度">
          <el-progress
            :percentage="calculateTotalProgress(currentStudent)"
            :status="getProgressStatus(currentStudent.status)"
          />
        </el-descriptions-item>
      </el-descriptions>

      <el-divider />

      <el-timeline>
        <el-timeline-item
          v-for="stage in currentStudent.stages"
          :key="stage.name"
          :type="getTimelineItemType(stage.status)"
          :color="getTimelineItemColor(stage.status)"
          :timestamp="stage.startTime"
          :hollow="stage.status === 'pending'"
        >
          <div class="timeline-content">
            <h4>{{ stage.name }}</h4>
            <div class="stage-details">
              <p>进度: {{ stage.progress }}%</p>
              <p>学时: {{ stage.hours }}课时</p>
              <p v-if="stage.examScore">考试成绩: {{ stage.examScore }}分</p>
              <p v-if="stage.remark">备注: {{ stage.remark }}</p>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>

    <!-- 进度更新对话框 -->
    <el-dialog
      v-model="updateDialogVisible"
      title="更新学习进度"
      width="500px"
    >
      <el-form :model="updateForm" label-width="100px">
        <el-form-item label="培训阶段">
          <el-select v-model="updateForm.stage" placeholder="请选择培训阶段">
            <el-option label="科目一" value="subject1" />
            <el-option label="科目二" value="subject2" />
            <el-option label="科目三" value="subject3" />
            <el-option label="科目四" value="subject4" />
          </el-select>
        </el-form-item>
        <el-form-item label="完成进度">
          <el-slider
            v-model="updateForm.progress"
            :step="5"
            show-input
          />
        </el-form-item>
        <el-form-item label="学时">
          <el-input-number
            v-model="updateForm.hours"
            :min="0"
            :step="0.5"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="考试成绩">
          <el-input-number
            v-model="updateForm.examScore"
            :min="0"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="updateForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitProgressUpdate">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import progressData from '@/data/studentProgressData.json'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  studentName: '',
  coachName: '',
  stage: ''
})

// 进度列表数据
const progressList = ref([]);

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 加载状态
const loading = ref(false)

// 对话框
const updateDialogVisible = ref(false)
const updateForm = reactive({
  stage: '',
  progress: 0,
  hours: 0,
  examScore: null,
  remark: ''
})

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    '未开始': 'info',
    '培训中': 'warning',
    '已完成': 'success',
    '已暂停': 'danger'
  }
  return types[status] || ''
}

// 获取时间线项目类型
const getTimelineItemType = (status) => {
  const types = {
    completed: 'success',
    in_progress: 'primary',
    pending: 'info'
  }
  return types[status] || ''
}

// 获取时间线项目颜色
const getTimelineItemColor = (status) => {
  const colors = {
    completed: '#67C23A',
    in_progress: '#409EFF',
    pending: '#909399'
  }
  return colors[status] || ''
}

// 处理静态数据
const processStaticData = (data) => {
  // 格式化静态数据以匹配组件所需格式
  return data.map(item => ({
    ...item,
    status: item.stages && item.stages.length > 0 && item.stages[item.stages.length - 1].status === 'completed' ? '已完成' : '进行中',
    currentStage: item.stages && item.stages.length > 0 ? item.stages[item.stages.length - 1].stageName : '未开始'
  }))
}

// 加载进度数据
const fetchProgressData = () => {
  loading.value = true
  try {
    // 调试信息
    console.log('开始加载数据...')
    console.log('progressData:', progressData)
    
    // 确保progressData是数组
    if (!Array.isArray(progressData)) {
      console.error('progressData不是数组:', progressData)
      ElMessage.error('数据格式错误')
      return
    }
    
    // 使用src目录中的JSON数据
    const processedData = processStaticData(progressData)
    console.log('处理后的数据:', processedData)
    
    // 简单分页处理
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    progressList.value = processedData.slice(startIndex, endIndex)
    total.value = processedData.length
    ElMessage.success('数据加载成功')
    console.log('数据加载成功，列表长度:', progressList.value.length)
  } catch (error) {
    ElMessage.error('获取进度数据失败')
    console.error('数据加载错误:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchProgressData()
})

// 计算总进度
const calculateTotalProgress = (student) => {
  if (!student.stages || student.stages.length === 0) return 0
  const total = student.stages.reduce((sum, stage) => sum + (stage.currentProgress || 0), 0)
  return Math.round(total / student.stages.length)
}

// 获取当前科目
const getCurrentSubject = (stages) => {
  if (!stages || stages.length === 0) return '未开始'
  const currentStage = stages.find(s => s.status === 'in_progress')
  if (currentStage) return currentStage.stageName
  const completedStage = stages.filter(s => s.status === 'completed').pop()
  return completedStage ? completedStage.stageName : stages[0]?.stageName || '未开始'
}

// 计算总学时
const calculateTotalHours = (stages) => {
  return stages.reduce((sum, stage) => sum + stage.hours, 0)
}

// 获取考试状态标签类型
const getExamStatusTagType = (status) => {
  const types = {
    '已通过': 'success',
    '未通过': 'danger',
    '待考试': 'warning',
    '未安排': 'info'
  }
  return types[status] || 'info'
}

// 获取进度条状态
const getProgressStatus = (status) => {
  const statusMap = {
    completed: 'success',
    in_progress: '',
    pending: 'info'
  }
  return statusMap[status] || ''
}

// 搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('搜索条件：', searchForm)
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 查看详情抽屉
const detailDrawerVisible = ref(false)
const currentStudent = ref({})

const handleViewDetails = (item) => {
  currentStudent.value = item
  detailDrawerVisible.value = true
}

// 更新进度
const handleUpdateProgress = (item) => {
  // 重置表单
  Object.assign(updateForm, {
    stage: '',
    progress: 0,
    hours: 0,
    examScore: null,
    remark: ''
  })
  updateDialogVisible.value = true
}

// 提交进度更新
const submitProgressUpdate = () => {
  if (!updateForm.stage) {
    ElMessage.warning('请选择培训阶段')
    return
  }
  // TODO: 实现进度更新逻辑
  console.log('更新进度：', updateForm)
  updateDialogVisible.value = false
  ElMessage.success('进度更新成功')
}

// 分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}
</script>

<style scoped>
.learning-progress {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.progress-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.student-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-text h3 {
  margin: 0;
  font-size: 16px;
  line-height: 1.5;
}

.info-text p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.progress-timeline {
  margin: 20px 0;
}

.timeline-content h4 {
  margin: 0 0 12px;
  font-size: 14px;
}

.stage-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.progress-bar {
  flex: 1;
}

.stage-details {
  min-width: 120px;
}

.stage-details p {
  margin: 4px 0;
  font-size: 13px;
  color: #606266;
}

.stage-remark {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 13px;
}

.card-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>